import { FrameworkConfigurator } from '../../framework-config';
import { EXTENSION_PATH, exeCommand, getExtensionConfig, getGamePacks, getFrameworkConfig, AssetDB } from '../../utils';

const os = require('os');
const fs = require('fs');
const path = require('path');
const vue = require('../../../../libs/vue.common.prod');

const econfig = getExtensionConfig();
const fconfig = getFrameworkConfig();
const frameworkConfig = new FrameworkConfigurator(fconfig);
const configModules = frameworkConfig.getConfigModules();
const gamePacks = getGamePacks();

// html 文本
export const template = `
<div id="${econfig.name}-settings" class="settings">
    <div class="slider">
        <ul>
            <li>
                <ui-label value="i18n:${econfig.name}.framework-function"></ui-label>
                <ul>
                    <li v-bind:active="showpage==0" v-on:click="changePage(0)">
                        <ui-label value="i18n:${econfig.name}.label-module-clip"></ui-label>
                    </li>
                </ul>
            </li>
        </ul>
    </div>
    <div class="content">
        <div v-show="showpage==0">
            <div>
                <ui-setting type="project" package="${econfig.name}" v-for="(module,i) in modules" v-bind:key="i">
                    <div>
                        <ui-checkbox style="width:30%;float:left;" v-bind:path="'modules.' + module.name" checked=""></ui-checkbox>
                        <ui-label v-bind:tooltip="module.description" style="width:70%;float:left;" v-bind:value="module.name"></ui-label>
                    </div>
                </ui-setting>
            </div>
            <div style="text-align:center;">
                <ui-button :disabled="doing" class="green" @click="applyMoudleClip()">${Editor.I18n.t(
                    econfig.name + '.button-apply-module'
                )}</ui-button>
            </div>
        </div>
    </div>
</div>
`;

// 样式文本
export const style =
    fs.readFileSync(path.join(EXTENSION_PATH, 'htmls', 'base-style.css'), { encoding: 'utf-8' }) +
    fs.readFileSync(path.join(EXTENSION_PATH, 'htmls', 'settings.css'), { encoding: 'utf-8' });

// 渲染后 html 选择器
export const $ = {
    panel: `#${econfig.name}-settings`
};

// 面板上的方法
export const methods = {};

// 面板上触发的事件
export const listeners = {
    /**
     * 面板隐藏的时候触发
     */
    hide() {
        // console.log(this.hidden);
    },
    /**
     * 面板显示的时候触发
     */
    show() {
        // console.log(this.hidden);
    },
    /**
     * 面板大小更改的时候触发
     */
    resize() {
        // console.log(this.clientHeight);
        // console.log(this.clientWidth);
    }
};

// 尝试关闭面板的时候触发
export async function beforeClose() {}

// 当面板实际关闭后触发
export async function close() {}

// 当面板渲染成功后触发
export async function ready() {
    let data = {
        showpage: 0,
        modules: configModules,
        doing: false
    };

    let methods = {
        /**
         * 改变选项卡
         *
         * @param page 页号
         */
        changePage: (page: number) => {
            if (data.showpage !== page) {
                data.showpage = page;
            }
        },

        /**
         * 应用模块裁剪
         */
        applyMoudleClip: async () => {
            data.doing = true;
            console.log('应用选择模块...');
            let saveMoudles: { [key: string]: boolean } = {};
            let frameworkConfig = new FrameworkConfigurator(fconfig);
            frameworkConfig.keepBaseModules();
            for (let module of configModules) {
                let save = await Editor.Profile.getProject(econfig.name, 'modules.' + module.name);
                if (save) {
                    frameworkConfig.keepModule(module.name);
                }
                saveMoudles[module.name] = save;
            }
            let changeMoudles: string[] = [];
            let keepModules = frameworkConfig.collectModules();
            for (let module of keepModules) {
                if (!saveMoudles[module.name]) {
                    await Editor.Profile.setProject(econfig.name, 'modules.' + module.name, true);
                    if (configModules.indexOf(module) > 0) {
                        changeMoudles.push(module.name);
                    }
                }
            }
            if (changeMoudles.length > 0) {
                console.warn(`由于依赖原因，下列模块需要保留:${changeMoudles.join(',')}`);
            }

            let modules = keepModules.map((v) => v.name).join(',');
            if (os.platform() === 'win32') {
                let command = `npx gulp buildAssets --modules "${modules}"`;
                let result = await exeCommand(command, EXTENSION_PATH);
                if (result.error) {
                    console.error(`error :\n${result.error}`);
                } else {
                    console.log(`stdout :\n${result.stdout}`);
                    if (result.stderr) {
                        console.error(`stderr :\n${result.stderr}`);
                    }
                }
                AssetDB.refreshAsset(`db://${econfig.name}/`);
            }
            console.log('应用选择模块完成');
            data.doing = false;
        }
    };

    // eslint-disable-next-line new-cap
    let vm = new vue({
        // eslint-disable-next-line @typescript-eslint/no-invalid-this
        el: this.$.panel,
        data: data,
        methods: methods
    });
}
